package com.group.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group.activity.dao.BargainGoodsDao;
import com.group.activity.dao.BargainUserDao;
import com.group.activity.entity.*;
import com.group.activity.vo.*;
import com.group.common.utils.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.group.activity.dao.BargainListDao;
import com.group.activity.service.BargainListService;
import org.springframework.util.StreamUtils;


@Service("bargainListService")
public class BargainListServiceImpl extends ServiceImpl<BargainListDao, BargainListEntity> implements BargainListService {

    @SuppressWarnings("all")
    @Autowired
    private StringUtils stringUtils;
    @Autowired
    private BargainListDao bargainListDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private BargainGoodsDao bargainGoodsDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private BargainUserDao bargainUserDao;
    @Autowired
    private SymmetricEncoder symmetricEncoder;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BargainListEntity> page = this.page(
                new Query<BargainListEntity>().getPage(params),
                new QueryWrapper<BargainListEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageInfo<BargainListVo> bargaininglist(BargaiListQueryVo bargaiListQueryVo) {
        PageHelper.startPage(bargaiListQueryVo.getPage(),bargaiListQueryVo.getSiz());
        List<BargainListVo> bargainListVos=bargainListDao.bargaininglist(bargaiListQueryVo);
        return new PageInfo<>(bargainListVos);
    }

    @Override
    public PageInfo<BargainUserVo> bargainingDetails(BargainUserQueryVo bargainUserQueryVo) {
        PageHelper.startPage(bargainUserQueryVo.getPage(),bargainUserQueryVo.getSize());
        List<BargainUserVo>bargainUserVos=bargainListDao.bargainingDetails(bargainUserQueryVo);
        return new PageInfo<>(bargainUserVos);
    }

    //主砍
    @Override
    public R bargainUser(BarUserVo barUserVo, Object user) {
        String s = JSON.toJSONString(user);
        //redis中取出当前登录用户
        ShopUserEntity shopUserEntity = JSONObject.parseObject(s, new TypeReference<ShopUserEntity>() {});
        if (shopUserEntity==null){
            return R.error("登录后才能砍价呦");
        }

        barUserVo.setUserId(shopUserEntity.getUserId());
        //判断该用户是否在进行砍价
        BargainListEntity userId = bargainListDao.selectOne(new QueryWrapper<BargainListEntity>().eq("user_id",barUserVo.getUserId()));

        if (userId!=null){
            return R.error("您正在进行砍价");
        }
        //保证锁的颗粒度
        RLock lock = redisson.getLock("anyLock_bargainGoodsId"+barUserVo.getBargainId());
        try{
            // 3. 尝试加锁，最多等待3秒，上锁以后5秒自动解锁
            boolean res = lock.tryLock(3,5, TimeUnit.SECONDS);
            if(res){    //成功
                Integer number = (Integer) redisTemplate.opsForValue().get(barUserVo.getBargainId()+"");
                if (number==null){
                    return R.error("系统操作繁忙");
                }
                if (number==0){
                    return R.error("当前砍价人数已达上限");
                }
                //减库存
                number--;
                redisTemplate.opsForValue().set(barUserVo.getBargainId()+"",number);
                //添加砍价列表
                //当前砍价商品的信息
                BargainGoodsEntity bargainGoodsId = bargainGoodsDao.selectOne(new QueryWrapper<BargainGoodsEntity>().eq("bargain_goods_id", barUserVo.getBargainId()));
                if(bargainGoodsId==null){
                    return R.error("砍价商品不存在 请重新输入");
                }
                //获取当前商品信息
                ShopCommodityEntity shopCommodityEntity=bargainListDao.shopList(bargainGoodsId.getShopId());
                //获取当前系统时间
                String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date newDate = simpleDateFormat.parse(now);
                //砍价列表
                BargainListEntity bargainListEntity = new BargainListEntity();
                //剩余砍价数 完成人数-1
                bargainListEntity.setTotalNumberOfCuts(1);
                bargainListEntity.setRemainingBargainingTimes(bargainGoodsId.getBargainingNumber()-1);
                bargainListEntity.setStartTime(newDate);
                bargainListEntity.setBargainingStatus(1);
                bargainListEntity.setBargainId(barUserVo.getBargainId());
                bargainListEntity.setUserId(barUserVo.getUserId());
                //添加用户记录表
                //添加砍价记录
                int i = bargainListDao.insert(bargainListEntity);
                //砍价用户记录表
                BargainUserEntity bargainUserEntity = new BargainUserEntity();
                bargainUserEntity.setStarttime(newDate);
                bargainUserEntity.setBargainListId(bargainListEntity.getBargainingListId());
                bargainUserEntity.setUserId(barUserVo.getUserId());
                BigDecimal bigDecimal = new BigDecimal("0.97");
                bargainUserEntity.setBargainPrice(shopCommodityEntity.getCommodityPrice().multiply(bigDecimal));
                if (i>0){
                    //将砍价信息放入延迟队列
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",bargainListEntity);
                    bargainUserDao.insert(bargainUserEntity);
                    return R.ok("开始砍价");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return null;
    }
    //帮砍
    @Override
    public R helpChop(String aesone, String aestwe, Object user) {
        //解密
        String bargaiingListId = symmetricEncoder.AESDncode("AES", aesone);
        String useId = symmetricEncoder.AESDncode("AES", aestwe);
        Integer bargainingListId = Integer.parseInt(bargaiingListId);
        Integer userId = Integer.parseInt(useId);
        if (bargaiingListId == null || useId == null) {
            return R.ok("访问地址不存在");
        }
        String s = JSON.toJSONString(user);
        //redisson中取出当前登录用户
        ShopUserEntity shopUserEntity = JSONObject.parseObject(s, new TypeReference<ShopUserEntity>() {});
        if (shopUserEntity == null) {
            return R.error("登录后才能帮好友进行砍价呦");
        }
        //保证锁的颗粒度
        RLock lock = redisson.getLock("anyLock_bargainListId" + bargainingListId);
        try {
            // 3. 尝试加锁，最多等待3秒，上锁以后5秒自动解锁
            boolean res = lock.tryLock(3, 5, TimeUnit.SECONDS);
            if (res) {    //成功
                //自己不能为自己砍
                if (userId == shopUserEntity.getUserId()) {
                    return R.error("请分享好友进行砍价");
                }
                //查询砍价信息
                BargainListEntity bargainListEntity = baseMapper.selectById(bargainingListId);
                if (bargainListEntity == null) {
                    return R.ok("砍价链接失效");
                }
                //判断砍价状态 成功 结束
                if (bargainListEntity.getBargainingStatus() == 3) {
                    return R.ok("商品已砍价成功");
                }
                if (bargainListEntity.getBargainingStatus() == 2) {
                    return R.ok("活动已结束");
                }
                //判断当前登录人 是否已帮砍
                BargainUserEntity bargainUserEntity = bargainUserDao.selectOned(bargainingListId, shopUserEntity.getUserId());
                if (bargainUserEntity != null) {
                    return R.ok("不能重复砍价o");
                }
                //查询商品砍价信息
                BargainGoodsEntity bargainGoodsEntity = bargainGoodsDao.selectById(bargainListEntity.getBargainId());
                //获取商品信息
                ShopCommodityEntity shopCommodityEntity = bargainListDao.shopList(bargainGoodsEntity.getShopId());
                //计算砍价金额
                BigDecimal bigDecimal = new BigDecimal("0.03");
                BigDecimal bigDecimalto = new BigDecimal(bargainGoodsEntity.getBargainingNumber() - 1);
                BigDecimal bigDecimalone = shopCommodityEntity.getCommodityPrice().multiply(bigDecimal);
                //获取系统时间
                String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date newDate = simpleDateFormat.parse(now);
                BargainUserEntity bargainUserEntity1 = new BargainUserEntity();
                //添加用户记录表记录表
                bargainUserEntity1.setStarttime(newDate);
                bargainUserEntity1.setBargainListId(bargainingListId);
                bargainUserEntity1.setUserId(shopUserEntity.getUserId());
                bargainUserEntity1.setBargainPrice(bigDecimalone.divide(bigDecimalto));
                int insert = bargainUserDao.insert(bargainUserEntity1);
                //修改砍价列表商品 帮砍价
                if (insert<0){
                   return R.error("系统繁忙");
                }
                bargainListEntity.setTotalNumberOfCuts(bargainListEntity.getTotalNumberOfCuts()+1);
                bargainListEntity.setRemainingBargainingTimes(bargainListEntity.getRemainingBargainingTimes()-1);
                int i = bargainListDao.updateById(bargainListEntity);
                if (i<0){
                  return R.error("系统繁忙");
                }
                if (bargainListEntity.getRemainingBargainingTimes()==0){
                    bargainListEntity.setBargainingStatus(3);
                    int i1 = bargainListDao.updateById(bargainListEntity);
                    if (i1<0){
                        return R.error("系统繁忙");
                    }
                    //减数据库
                    bargainGoodsEntity.setNumberOfSuccessfulBargaining(bargainGoodsEntity.getNumberOfSuccessfulBargaining()+1);
                    bargainGoodsEntity.setBargainGoodsLimitedsurplus(bargainGoodsEntity.getBargainGoodsLimitedsurplus()-1);
                    int i2 = bargainGoodsDao.updateById(bargainGoodsEntity);
                    if (i2<0){
                        return R.error("系统繁忙");
                    }
                   return R.ok("好友已砍价成功");
                }
                return R.ok("帮砍成功");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return null;
    }


}
